package cli

import (
	"github.com/eiannone/keyboard"
)

type KeyBoardListener struct {
	keysEvents <-chan keyboard.KeyEvent
	err        error
	run        bool
}

func (listener *KeyBoardListener) Stop() {
	listener.run = false
}

func (listener *KeyBoardListener) Listener() <-chan string {
	listener.run = true
	input := make(chan string)
	go func() {
		defer func() {
			close(input)
			_ = keyboard.Close()
		}()
		listener.keysEvents, listener.err = keyboard.GetKeys(10)

		for event := range listener.keysEvents {
			if listener.run == false {
				func() {
					defer func() {
						recover()
					}()
					close(input)
				}()
				break
			}

			if event.Err != nil {
				panic(event.Err)
			}
			tmp := string(event.Rune)
			if tmp == "\x00" {
				if event.Key == keyboard.KeyEsc {
					tmp = "esc"
				} else if event.Key == keyboard.KeyArrowUp {
					tmp = "up"
				} else if event.Key == keyboard.KeyArrowDown {
					tmp = "down"
				} else if event.Key == keyboard.KeyArrowLeft {
					tmp = "left"
				} else if event.Key == keyboard.KeyArrowRight {
					tmp = "right"
				} else if event.Key == keyboard.KeyEnter {
					tmp = "enter"
				}
			}
			input <- tmp

			if listener.run == false {
				func() {
					defer func() {
						recover()
					}()
					close(input)
				}()
				break
			}
		}

		for {
			if listener.run == false {
				func() {
					defer func() {
						recover()
					}()
					close(input)
				}()
				break
			}
		}
	}()
	return input
}
